package com.future.hedongjun.mine.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.future.baselib.activity.BaseActivity;
import com.future.baselib.entity.BaseResponse;
import com.future.baselib.entity.MessageEvent;
import com.future.baselib.http.HttpRequest;
import com.future.baselib.utils.EventBusUtil;
import com.future.baselib.utils.PatternUtils;
import com.future.hedongjun.R;
import com.future.hedongjun.common.Contant;
import com.future.hedongjun.common.MyApp;
import com.future.hedongjun.mine.bean.response.UserInfoResponse;
import com.jaeger.library.StatusBarUtil;


import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.PlatformDb;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.utils.WechatClientNotExistException;

public class LoginActivity extends BaseActivity implements PlatformActionListener {

    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.et_password)
    EditText etPassword;
    @BindView(R.id.btn_login)
    Button btnLogin;
    @BindView(R.id.tv_forget_password)
    TextView tvForgetPassword;
    @BindView(R.id.tv_register)
    TextView tvRegister;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        setTitle("登录");
    }

    @OnClick({R.id.btn_login, R.id.tv_forget_password, R.id.tv_wechat, R.id.tv_qq, R.id.tv_weibo, R.id.tv_register})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_login:
                login();
                break;
            case R.id.tv_forget_password:
                Bundle bundle = new Bundle();
                bundle.putInt("type", 2);
                startActivity(RegisterActivity.class, bundle);
                break;
            case R.id.tv_wechat:
//                bindingPhone();
                Platform wechat = ShareSDK.getPlatform(Wechat.NAME);
                wechat.setPlatformActionListener(this);
                wechat.authorize();
                break;
            case R.id.tv_qq:
//                bindingPhone();
                Platform qq = ShareSDK.getPlatform(QQ.NAME);
                qq.setPlatformActionListener(this);
                qq.authorize();
                break;
            case R.id.tv_weibo:
//                bindingPhone();
                Platform weibo = ShareSDK.getPlatform(SinaWeibo.NAME);
                weibo.setPlatformActionListener(this);
                weibo.authorize();
                break;
            case R.id.tv_register:
                startActivityForResult(RegisterActivity.class, 0x123);
                break;
        }
    }

    @SuppressWarnings("unchecked")
    private void login() {
        final String mobile = etPhone.getText().toString().trim();
        if (!PatternUtils.mobilePattern(toast, mobile)) {
            return;
        }
        String password = etPassword.getText().toString();
        if (!PatternUtils.passwordPattern(toast, password)) {
            return;
        }
        new HttpRequest<UserInfoResponse>()
                .with(this)
                .setPath("/api/User/login")
                .addParam("account", mobile)
                .addParam("password", password)
                .addSuccessListener(new HttpRequest.OnNetworkSuccess() {
                    @Override
                    public void onSuccess(BaseResponse response) {
                        MyApp.getInstance().setUserInfo(((UserInfoResponse) response).userInfo);
                        EventBusUtil.sendEvent(new MessageEvent(Contant.EVENT_CODE_LOGIN));
                        finish();
                    }
                }).start(new UserInfoResponse());
    }

    @SuppressWarnings("unchecked")
    @Override
    public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
        final PlatformDb db = platform.getDb();
//        String string = new StringBuffer().append("平台：").append(db.getPlatformNname()).append("   成功").toString();
//        toast(string);

        String platKey = "qq";
        if (db.getPlatformNname().equals(QQ.NAME)) {
            platKey = "qq";
        } else if (db.getPlatformNname().equals(Wechat.NAME)) {
            platKey = "wx";
        } else if (db.getPlatformNname().equals(SinaWeibo.NAME)) {
            platKey = "wb";
        }

        final String finalPlatKey = platKey;
        new HttpRequest<UserInfoResponse>()
                .with(this)
                .setPath("/api/User/thirdlogin")
                .addParam("platform",platKey)
                .addParam("openid", db.getToken())
                .addSuccessListener(new HttpRequest.OnNetworkSuccess() {
                    @Override
                    public void onSuccess(BaseResponse response) {
                        MyApp.getInstance().setUserInfo(((UserInfoResponse) response).userInfo);
                        EventBusUtil.sendEvent(new MessageEvent(Contant.EVENT_CODE_LOGIN));
                        finish();
                    }
                })
                .addFailListener(new HttpRequest.OnNetworkFail() {
                    @Override
                    public void onFail(String message) {
                        if (message.equals("该openid还未绑定手机号")) {
                            Bundle bundle = new Bundle();
                            bundle.putString("token", db.getToken());
                            bundle.putString("nickname", db.getUserName());
                            bundle.putString("avatar_url", db.getUserIcon());
                            bundle.putString("platKey", finalPlatKey);
                            bundle.putInt("type", 3);
                            startActivityForResult(RegisterActivity.class, bundle, 0x123);
                        }
                    }
                })
                .start(new UserInfoResponse());

//        new HttpRequest.OnNetworkListener() {
//            @Override
//            public void onSuccess(BaseResponse response) {
//                MyApp.setUserToken(((UserInfoResponse) response).userToken);
//                MyApp.setUserType(values);
//                UserInfoSpHelper.setParams(LoginActivity.this,"userToken", ((UserInfoResponse) response).userToken);
//                UserInfoSpHelper.setParams(LoginActivity.this,"user_type", values);
//                finish();
//            }
//
//            @Override
//            public void onFail(String message) {
//                else {
//                    toast(message);
//                }
//            }
//        }
    }

    @Override
    public void onError(Platform platform, int i, Throwable throwable) {
        if (throwable instanceof WechatClientNotExistException) {
            toast("微信客户端不存在");
        } else {
            toast(throwable.getMessage());
        }
    }

    @Override
    public void onCancel(Platform platform, int i) {
        toast("取消登录");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == resultCode && requestCode == 0x123) {
            finish();
        }
    }
}
